﻿using CHSystemApi.Framework.AuthServices;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;

namespace CHSystemApi.Framework
{
    public static class Services
    {
        /// <summary>
        /// Redis依赖注入方法
        /// </summary>
        /// <param name="service"></param>
        /// <param name="connectionstring"></param>
        /// <returns></returns>
        public static IServiceCollection AddRedisCache(this IServiceCollection service, string connectionstring)
        {
            service.AddSingleton(serviceprovider =>
            {
                var configuration = ConfigurationOptions.Parse(connectionstring, true);

                configuration.ResolveDns = true;

                return ConnectionMultiplexer.Connect(configuration);
            });

            return service.AddTransient<CHSystemApi.Framework.Redis.IRedis, CHSystemApi.Framework.Redis.Redis>();
        }

        /// <summary>
        /// 添加JWT服务
        /// </summary>
        /// <param name="validIssuer">签发</param>
        /// <param name="validAudience">受众</param>
        /// <param name="issuerSigningKey">密钥</param>
        public static void AddJwtService(this IServiceCollection service, string validIssuer, string validAudience, SymmetricSecurityKey issuerSigningKey)
        {
            service.AddAuthentication(x =>
             {
                 x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                 x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
             }).AddJwtBearer(x =>
             {
                 x.TokenValidationParameters = new TokenValidationParameters()
                 {
                     ValidateIssuer = true,
                     ValidIssuer = validIssuer,
                     ValidAudience = validAudience,
                     IssuerSigningKey = issuerSigningKey,
                     ValidateAudience = true,
                     ValidateIssuerSigningKey = true,
                     ValidateLifetime = true,
                     RequireExpirationTime = true
                 };
             });
        }
    }
}
